﻿using NAudio.CoreAudioApi;
using NAudio.CoreAudioApi.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation.Collections;

namespace Xiaowei
{
    class MicrophoneStateDetector : IMMNotificationClient, IDisposable
    {
        private int microphoneCount = 2;
        private MMDeviceEnumerator DevEnum = null;
        private static MicrophoneStateDetector detector = null;
        public static void Create()
        {
            if(detector == null)
            {
                detector = new MicrophoneStateDetector();
            }
        }

        public static void Destroy()
        {
            if(detector != null)
            {
                detector.Dispose();
                detector = null;
            }
        }
        public MicrophoneStateDetector()
        {
            DevEnum = new MMDeviceEnumerator();
            DevEnum.RegisterEndpointNotificationCallback(this);
            UpdateMicrophoneState();
        }

        public void OnDefaultDeviceChanged(DataFlow flow, Role role, string defaultDeviceId)
        {
            UpdateMicrophoneState();
        }

        public void OnDeviceAdded(string pwstrDeviceId)
        {
            UpdateMicrophoneState();
        }

        public void OnDeviceRemoved(string deviceId)
        {
            UpdateMicrophoneState();
        }

        public void OnDeviceStateChanged(string deviceId, DeviceState newState)
        {
            UpdateMicrophoneState();
        }

        public void OnPropertyValueChanged(string pwstrDeviceId, PropertyKey key)
        {
            UpdateMicrophoneState();
        }

        public void Dispose()
        {
            if (DevEnum != null)
            {
                DevEnum.Dispose();
                DevEnum = null;
            }
        }
        
        private void UpdateMicrophoneState()
        {
            //if (DevEnum != null)
            //{
            //    MMDeviceCollection devices = DevEnum.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active);
            //    if (devices.Count != microphoneCount)
            //    {
            //        microphoneCount = devices.Count;
            //        Connection.SendMessage(new ValueSet() { { "Request", "MicrophoneState" }, { "Active", microphoneCount != 0 } });
            //    }
            //}
        }
    }
}
